package com.hanxiaozhang.no10leetcode;

import java.util.Arrays;

/**
 * 〈一句话功能简述〉<br>
 * 〈翻转字符串〉
 * <p>
 * 编写一个函数，其作用是将输入的字符串反转过来。输入字符串以字符数组s的形式给出。
 * 示例 1：
 * 输入：s = ["h","e","l","l","o"]
 * 输出：["o","l","l","e","h"]
 * <p>
 * 示例 2：
 * 输入：s = ["H","a","n","n","a","h"]
 * 输出：["h","a","n","n","a","H"]
 * <p>
 * 思路：
 * 找到中间位置，然后前后位置调换。
 *
 * @author hanxinghua
 * @create 2024/1/4
 * @since 1.0.0
 */
public class No344ReverseString {


    public static void main(String[] args) {

        System.out.println("前置知识点：");
        System.out.println("8/2 = " + 8 / 2);
        System.out.println("9/2 = " + 9 / 2);

        char[] s1 = {'h', 'e', 'l', 'l', 'o'};
        char[] s2 = {'H', 'a', 'n', 'n', 'a', 'h'};

        System.out.println("---- ---- ---- ----");
        System.out.println(Arrays.toString(method1(s1)));
        System.out.println(Arrays.toString(method1(s2)));

        System.out.println("---- ---- ---- ----");
        System.out.println(Arrays.toString(method2(s1)));
        System.out.println(Arrays.toString(method2(s2)));

    }

    /**
     * 方法2
     *
     * @param s
     * @return
     */
    private static char[] method2(char[] s) {

        // 特殊值校验
        if (s == null || s.length < 2) {
            return s;
        }

        for (int i = 0; i < s.length / 2; i++) {
            char temp = s[i];
            s[i] = s[s.length - 1 - i];
            s[s.length - 1 - i] = temp;

//            // 另一种写法
//            s[i] ^=  s[s.length - 1 - i];
//            s[s.length - 1 - i] ^= s[i];
//            s[i] ^= s[s.length - 1 - i];
        }
        return s;
    }


    /**
     * 方法1
     *
     * @param s
     * @return
     */
    private static char[] method1(char[] s) {

        // 特殊值校验
        if (s == null || s.length < 2) {
            return s;
        }

        char[] result = new char[s.length];
        for (int i = 0; i < s.length; i++) {
            result[s.length - 1 - i] = s[i];
        }
        return result;
    }


}
